<template>
  <div class="patient-control-container" style="height: 100%; width: 100%; margin: 0; padding: 0;">
    <!-- 查询条件表单 - 优化布局 -->
    <el-form :inline="true" :model="queryForm" class="demo-form">
      <el-form-item label="科室">
        <el-select v-model="queryForm.department" placeholder="请选择科室" clearable style="width: 150px;">
          <el-option label="全部" value="全部"></el-option>
          <el-option label="造口护理" value="造口护理"></el-option>
          <el-option label="前列腺癌" value="前列腺癌"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button type="primary" @click="showAddDialog = true" class="add-button ml-2">
          <i class="el-icon-plus"></i> 增加用户
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 表格标题和新增按钮 -->
    <div class="table-header">
      <h3 class="table-title">用户信息列表</h3>
      <div class="table-info">
        <span class="total-count">共 {{ total }} 条记录</span>
      </div>
    </div>

    <!-- 表格部分 - 占满剩余空间 -->
    <el-table
        :data="userInfo"
        border
        style="width: 100%; height: calc(100% - 180px); margin: 0;"
        :row-style="{ height: '48px' }"
        :cell-style="{ padding: '0' }"
    >
      <el-table-column prop="username" label="用户名" min-width="80px"></el-table-column>
      <el-table-column prop="authority" label="科室" min-width="80px"></el-table-column>
      <el-table-column fixed="right" label="操作" min-width="120px">
        <template v-slot:default="scope">
          <el-button type="text" size="small" @click="handleResetPassword(scope.row)">
            <i class="el-icon-refresh"></i> 重置密码
          </el-button>
          <el-button type="text" size="small" @click="handleDelete(scope.row)">
            <i class="el-icon-delete"></i> 删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页部分 -->
    <el-row style="margin-top: 10px; width: 100%;">
      <el-col :span="24">
        <el-pagination
            @size-change="sizeChange"
            @current-change="currentChange"
            :current-page="page"
            :page-size="size"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
        ></el-pagination>
      </el-col>
    </el-row>

    <!-- 增加用户弹窗 -->
    <el-dialog title="增加用户" v-model="showAddDialog" width="25%">
      <div style="display: flex; justify-content: center; flex-direction: column; padding: 20px;">
        <el-input
            v-model="addUserForm.username"
            placeholder="请输入用户名"
            style="width: 100%; margin-bottom: 15px;"
        ></el-input>
        <el-input
            v-model="addUserForm.password"
            type="password"
            placeholder="请输入密码"
            style="width: 100%; margin-bottom: 15px;"
        ></el-input>
        <el-select
            v-model="addUserForm.authority"
            placeholder="请选择科室"
            style="width: 100%;"
        >
          <el-option label="造口护理" value="造口护理"></el-option>
          <el-option label="前列腺癌" value="前列腺癌"></el-option>
        </el-select>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddDialog = false">取消</el-button>
          <el-button type="primary" @click="handleAdd">提交</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改用户弹窗（保留但不再使用） -->
    <!-- <el-dialog title="修改用户" v-model="showEditDialog" width="25%">
      <div style="display: flex; justify-content: center; flex-direction: column; padding: 20px;">
        <el-input
            v-model="editUserForm.username"
            placeholder="请输入用户名"
            style="width: 100%; margin-bottom: 15px;"
        ></el-input>
        <el-input
            v-model="editUserForm.password"
            type="password"
            placeholder="请输入密码"
            style="width: 100%; margin-bottom: 15px;"
        ></el-input>
        <el-input
            v-model="editUserForm.authority"
            placeholder="请输入科室"
            style="width: 100%;"
        ></el-input>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showEditDialog = false">取消</el-button>
          <el-button type="primary" @click="handleUpdate">提交</el-button>
        </span>
      </template>
    </el-dialog> -->
  </div>
</template>

<script>
import { ref } from 'vue';
import { apiClient } from '../api/apiClient';
import { ElMessage, ElMessageBox } from 'element-plus';

export default {
  setup() {
    // 查询条件
    const queryForm = ref({
      department: '全部'
    });

    // 增加用户相关
    const showAddDialog = ref(false);
    const addUserForm = ref({
      username: '',
      password: '',
      authority: '造口护理'
    });

    // 修改用户相关（保留但不再使用）
    const showEditDialog = ref(false);
    const editUserForm = ref({
      username: '',
      password: '',
      authority: ''
    });
    const originalUsername = ref('');

    // 表格数据相关
    const page = ref(1);
    const size = ref(10);
    const total = ref(0);
    const allUserInfo = ref([]);
    const userInfo = ref([]);

    const handleQuery = async () => {
      try {
        const response = await apiClient.get('/doctor/getAllDoctorInfo', {
          params: {
            department: queryForm.value.department
          }
        });

        if (response.data.code === 1) {
          // 获取原始数据
          let allData = response.data.data;

          // 根据科室筛选数据（只保留造口护理和前列腺癌）
          allUserInfo.value = allData.filter(item => {
            const validAuthorities = ['造口护理', '前列腺癌'];
            return validAuthorities.includes(item.authority);
          });

          total.value = allUserInfo.value.length;
          getTableData();
          //ElMessage.success('数据加载成功');
        } else {
          console.error('Failed to fetch user info:', response.data.msg);
          ElMessage.error('获取数据失败，请稍后重试');
        }
      } catch (error) {
        console.error('Failed to fetch user info:', error);
        ElMessage.error('网络请求失败，请稍后重试');
      }
    };

    const handleAdd = async () => {
      if (!addUserForm.value.username || !addUserForm.value.password || !addUserForm.value.authority) {
        ElMessage.error('请填写完整的用户信息');
        return;
      }
      if (addUserForm.value.authority === '全部') {
        ElMessage.error('添加失败:科室不存在');
        return;
      }
      try {
        await ElMessageBox.confirm(
            `确定要添加用户 ${addUserForm.value.username} 吗？`,
            '确认添加',
            {
              confirmButtonText: '确认',
              cancelButtonText: '取消',
              type: 'warning'
            }
        );

        const response = await apiClient.post('/doctor/register', addUserForm.value);

        if (response.data.code === 1) {
          ElMessage.success('成功添加用户');
          addUserForm.value = {
            username: '',
            password: '',
            authority: ''
          };
          showAddDialog.value = false;
          handleQuery(); // 添加成功后刷新数据
        } else {
          ElMessage.error(`添加失败: ${response.data.msg || '未知错误'}`);
        }
      } catch (error) {
        if (error === 'cancel') return;
        console.error('添加用户失败:', error);
        ElMessage.error('网络请求失败，请稍后重试');
      }
    };

    // 替换原有的handleEdit和handleUpdate方法
    const handleResetPassword = async (row) => {
      try {
        await ElMessageBox.confirm(
            `确定要将用户 ${row.username} 的密码重置为123456吗？`,
            '确认重置密码',
            {
              confirmButtonText: '确认',
              cancelButtonText: '取消',
              type: 'warning'
            }
        );

        const resetData = {
          username: row.username,
          password: '123456',
          authority: row.authority
        };

        const response = await apiClient.put(`/doctor/reset?yusernam=${row.username}`, resetData);

        if (response.data.code === 1) {
          ElMessage.success('密码重置成功');
          handleQuery(); // 重置成功后刷新数据
        } else {
          ElMessage.error(`重置失败: ${response.data.msg || '未知错误'}`);
        }
      } catch (error) {
        if (error === 'cancel') return;
        console.error('重置密码失败:', error);
        ElMessage.error('网络请求失败，请稍后重试');
      }
    };

    const handleDelete = async (row) => {
      try {
        await ElMessageBox.confirm(
            `确定删除该用户 ${row.username} 吗？`,
            '确认删除',
            {
              confirmButtonText: '删除',
              cancelButtonText: '取消',
              type: 'error'
            }
        );

        const response = await apiClient.delete(`/doctor/deletUser?username=${row.username}`);

        if (response.data.code === 1) {
          ElMessage.success(`成功删除用户: ${row.username}`);
          handleQuery(); // 删除成功后刷新数据
        } else {
          ElMessage.error(`删除失败: ${response.data.msg || '未知错误'}`);
        }
      } catch (error) {
        if (error === 'cancel') return;
        console.error('删除用户失败:', error);
        ElMessage.error('网络请求失败，请稍后重试');
      }
    };

    const getTableData = () => {
      userInfo.value = allUserInfo.value.slice((page.value - 1) * size.value, page.value * size.value);
    };

    const sizeChange = (newSize) => {
      size.value = newSize;
      getTableData();
    };

    const currentChange = (newPage) => {
      page.value = newPage;
      getTableData();
    };

    return {
      queryForm,
      showAddDialog,
      addUserForm,
      showEditDialog,
      editUserForm,
      page,
      size,
      total,
      userInfo,
      handleQuery,
      handleAdd,
      handleResetPassword,
      handleDelete,
      getTableData,
      sizeChange,
      currentChange
    };
  }
};
</script>

<style scoped>
.patient-control-container {
  box-sizing: border-box;
  margin: 0;
  padding: 20px;
}

.demo-form {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 15px;
  width: 100%; /* 确保表单占满宽度 */
  box-sizing: border-box;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  width: 100%; /* 确保标题栏占满宽度 */
  box-sizing: border-box;
}

.table-title {
  font-size: 18px;
  font-weight: 500;
  color: #303133;
  margin: 0;
}

.table-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.total-count {
  color: #606266;
  font-size: 14px;
}

.add-button {
  display: flex;
  align-items: center;
}

.ml-2 {
  margin-left: 10px;
}
</style>